package service

import (
	"bufio"
	"crypto/sha256"
	"fmt"
	"gcopyright/models"
	"gcopyright/repositories"
	"github.com/kataras/iris"
	"os"
	"time"
)

type FileService struct {
	ctx iris.Context
	sql *repositories.RepositoriesSqlite
}

func NewFileService(c iris.Context, s *repositories.RepositoriesSqlite) *FileService {
	return &FileService{ctx: c, sql: s}
}

func (f *FileService) Parser() models.FileInfo {
	var info = models.FileInfo{
		Author:       f.ctx.URLParam("author"),
		Content:      f.ctx.URLParam("content"),
		ContentShort: f.ctx.URLParam("content_short"),
		TimeStamp:    time.Now().Unix(),
		Title:        f.ctx.URLParam("title"),
	}
	return info
}

func (f *FileService) StorageInfo(info models.FileInfo) models.ModifyFile { // 名字 ， 路径 ， 全名 ， 内容
	fName := info.Title + ".html"
	ether := os.Getenv("ETHER")
	fPath := ether + "\\files\\"
	fPathName := ether + "\\files\\" + fName
	file, err := os.Create(fPathName)
	check(err)
	defer file.Close()
	fileWrite := bufio.NewWriter(file)
	fmt.Println()
	fileContent := info.Content +
		"<p>===========</P>" +
		"<p>标题: " + info.Title + "</p>" +
		"<p>作者: " + info.Author + "</p>" +
		"<p>时间戳: " + fmt.Sprintf("%d", info.TimeStamp) + "</p>"
	_, err = fileWrite.WriteString(fileContent)
	check(err)
	check(fileWrite.Flush())
	var modifyInfo = models.ModifyFile{
		FName:       fName,
		FPath:       fPath,
		FPathName:   fPathName,
		FileContent: fileContent,
		Hash:        "000000",
	}
	return modifyInfo
}

func (f *FileService) GetFileHash(file models.ModifyFile) models.ModifyFile {
	Sha256Inst := sha256.New()
	Sha256Inst.Write([]byte(file.FileContent))
	Result := Sha256Inst.Sum([]byte(""))
	file.Hash = fmt.Sprintf("%x", Result)

	return file
}

func (f *FileService) ModifyName(file models.ModifyFile) {
	err := os.Rename(file.FPathName, file.FPath+file.Hash)
	check(err)
}

func (f *FileService) ModifyFile() models.ModifyFile {
	par := f.Parser()

	sto := f.StorageInfo(par)
	FileHash := f.GetFileHash(sto)
	f.ModifyName(FileHash)
	f.sql.InsertFileInfoTable(par.Author, par.Content, par.ContentShort, FileHash.Hash, par.Title, par.TimeStamp)
	return FileHash
}

func (f *FileService) DeleteFile() {
	hash := f.ctx.URLParam("hash")
	f.sql.DeleteFileInfoTableElement(hash)
	ether := os.Getenv("ETHER")
	if os.Remove(ether+"\\files\\"+hash) != nil {
		fmt.Println("Delete fail")
	}
}
